package com.my.socket.nio.v26;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by ZhongGang
 * at 2018/8/20 17:15
 */
public class Acceptor implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Acceptor.class);

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;

    Acceptor(Selector selector, ServerSocketChannel serverSocketChannel) {
        this.selector = selector;
        this.serverSocketChannel = serverSocketChannel;
    }

    @Override
    public void run() {
        try {
            SocketChannel socketChannel = this.serverSocketChannel.accept();
            if (socketChannel != null) {
                LOGGER.info("incoming socket: {}", socketChannel);
                new Handler(this.selector, socketChannel);
            }
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
        }
    }
}
